import java.awt.image.BufferedImage;
import java.io.File;
import javax.imageio.ImageIO;

/**
 * 对比度算法
 */
public class ImageContrastEnhancement {
    public static void main(String[] args) {
        try {
            File input = new File("src\\main\\resources\\tess4j\\split\\33.png");
            BufferedImage image = ImageIO.read(input);

            float contrastFactor = 0.0f;
            while (contrastFactor < 20.0) {
                BufferedImage enhancedImage = enhanceContrast(image, contrastFactor); // 对比度因子，可以根据需要调整
                File output = new File(input.getParentFile() + "\\33\\对比度\\" + contrastFactor + ".jpg");
                ImageIO.write(enhancedImage, "jpg", output);
                contrastFactor = contrastFactor + 0.1f;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static BufferedImage enhanceContrast(BufferedImage image, float contrastFactor) {
        int width = image.getWidth();
        int height = image.getHeight();
        BufferedImage newImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        for (int y = 0; y < height; y++) {
            for (int x = 0; x < width; x++) {
                int argb = image.getRGB(x, y);
                int alpha = (argb >> 24) & 0xff;
                int red = (argb >> 16) & 0xff;
                int green = (argb >> 8) & 0xff;
                int blue = argb & 0xff;
                red = Math.min(255, Math.max(0, (int)(contrastFactor * (red - 128) + 128)));
                green = Math.min(255, Math.max(0, (int)(contrastFactor * (green - 128) + 128)));
                blue = Math.min(255, Math.max(0, (int)(contrastFactor * (blue - 128) + 128)));
                int newPixel = (alpha << 24) | (red << 16) | (green << 8) | blue;
                newImage.setRGB(x, y, newPixel);
            }
        }
        return newImage;
    }
}